package com.i2863.receipt.api;

import com.alibaba.fastjson.JSONObject;
import com.i2863.receipt.entity.Activity;
import com.i2863.receipt.entity.Receipt;
import com.i2863.receipt.entity.Site;
import com.i2863.receipt.entity.Winner;
import com.i2863.receipt.service.ActivityService;
import com.i2863.receipt.service.ReceiptService;
import com.i2863.receipt.service.SiteService;
import com.i2863.receipt.service.WinnerService;
import com.i2863.receipt.util.ApiResultJson;
import com.i2863.receipt.util.ResultJson;
import com.i2863.receipt.vo.WinnerVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * APP接口
 * Created by Administrator on 2018/6/11.
 */
@RestController
@RequestMapping("/app")
public class APPInterface {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private ReceiptService receiptService;

    @Autowired
    private SiteService siteService;

    @Autowired
    private WinnerService winnerService;

    private final static Logger logger = LoggerFactory.getLogger(APPInterface.class);

    /**
     * 报名接口
     */
    @RequestMapping("/addreceipt")
    public String addReceipt(@RequestParam(value = "code",required = true)String code,
                             @RequestParam(value = "businessName",required = true)String businessName,
                             @RequestParam(value = "codeNum",required = true)String codeNum,
                             @RequestParam(value = "money",required = true)Double money,
                             @RequestParam(value = "receiptDate",required = true)String receiptDate,
                             @RequestParam(value = "phoneNum",required = true)String phoneNum,
                             @RequestParam(value = "siteId",required =  true)Integer siteId){

        Receipt receipt = receiptService.findByCode(code);
        if(receipt!=null){
            return ApiResultJson.errorMes(ApiResultJson.RECEIPT_EXISTS,"发票已存在");
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 hh时:mm分:ss秒");
        Date receipt_Date;//转换发票时间
        try {
            receipt_Date = format.parse(receiptDate+" 12时:00分:00秒");
        } catch (ParseException e) {
            e.printStackTrace();
            logger.error("时间格式转换异常");
            return ApiResultJson.errorMes(ApiResultJson.DATA_ABNORMAL,"时间格式异常");
        }
        List<Activity> activitys = activityService.findOneByNow(siteId);
//        System.out.println(receipt_Date.getTime());
//        System.out.println(activitys.get(0).getStartTime().getTime());
//        System.out.println(activitys.get(0).getEndTime().getTime());
        if(activitys==null||activitys.size()==0){//当前时间没有活动
            return ApiResultJson.errorMes(ApiResultJson.ACTIVITY_UNDEFINE,"活动不存在");
        }
//        if(!activity.getStartTime().before(receipt_Date)||!activity.getEndTime().after(receipt_Date)){
        if((activitys.get(0).getStartTime().getTime()>receipt_Date.getTime())||(activitys.get(0).getEndTime().getTime()<receipt_Date.getTime())){
            return ApiResultJson.errorMes(ApiResultJson.RECEIPTDATE_INCONFORMITY,"发票时间不符合当前一期活动时间");
        }
        if(activitys.get(0).getAmountLow()>money){
            return ApiResultJson.errorMes(ApiResultJson.RECEIPTMONEY_INSUFFICIENT,"发票金额不足");
        }
        if(StringUtils.isBlank(businessName)){
            return ApiResultJson.errorMes(ApiResultJson.BUSINESSNAME_NULL,"商户名称为不能为空");
        }
        Receipt entity = new Receipt();
        entity.setActivity(activitys.get(0));
        entity.setCode(code);
        entity.setCodeNum(codeNum);
        entity.setPhoneNum(phoneNum);
        entity.setMoney(money);
        entity.setReceiptDate(receipt_Date);
        entity.setBusinessName(businessName);
        receiptService.add(entity);
        return ResultJson.successMeg(200,"报名成功");
    }


    /**
     * 电话号码查询-
     * @param phoneNum-
     * @param siteId
     * @return
     */
    @RequestMapping("/querywinner")
    public String queryWinner(@RequestParam(value = "phoneNum",required = true)String phoneNum,
                              @RequestParam(value = "siteId",required = true)Integer siteId,
                              @RequestParam(value = "lastId",required = false,defaultValue = "0")Integer lastId){
        Page<Winner> page = winnerService.findByPhoneNumAndSiteId(phoneNum,siteId,lastId,1);
        List<Winner> winnerList = page.getContent();
        if(winnerList==null||winnerList.size()==0){//未查询到数据
            return ApiResultJson.errorMes(ApiResultJson.NO_DATA,"没有查询到数据");
        }
        List<WinnerVo> winnerVos = new ArrayList<WinnerVo>();
        for (Winner winner : winnerList) {
            WinnerVo vo = new WinnerVo();
            vo.setId(winner.getId());
            vo.setWinPhoneNum(winner.getWinPhoneNum());
            vo.setReceiptDate(winner.getReceiptDate());
            vo.setMoney(winner.getMoney().doubleValue());
            vo.setActivity(winner.getActivity().getName());
            vo.setIsInside(winner.getIsInside());
            vo.setIsReselection(winner.getIsReselection());
            vo.setLevel(winner.getLevel());
            vo.setLevelName(winner.getLevelName());
            vo.setPrize(winner.getPrize());
            vo.setPrizeName(winner.getPrizeName());
            vo.setReceiptCode(winner.getReceiptCode());
            vo.setReceiptCodeNum(winner.getReceiptCodeNum());
            vo.setReceiptMoney(winner.getReceiptMoney());
            vo.setReceiptCode(winner.getReceiptCode());
            vo.setReceiptCodeNum(winner.getReceiptCodeNum());
            winnerVos.add(vo);
        }
        return ApiResultJson.successResult(ApiResultJson.SUCCESS,"",winnerVos);
    }


    /**-
     * 获取当前站点的当前活动信息
     * @param siteId
     * @return
     */
    @RequestMapping("/getcurrentactivity")
    public String getCurrentActivity(@RequestParam(value = "siteId")Integer siteId){
        //查询站点下的当前的活动，获取信息
        List<Activity> activitys = activityService.findOneByNow(siteId);
        if(activitys==null||activitys.size()==0){
            return ApiResultJson.errorMes(ApiResultJson.NO_DATA,"当前没有活动");
        }
        return ApiResultJson.successResult(ApiResultJson.SUCCESS,"",activitys.get(0));
    }


    @RequestMapping("/getImg")
    public String getImg(@RequestParam(value = "siteId")Integer siteId){
        Site site = siteService.findOne(siteId);
        String ImgUrl = site.getImgUrl();
        if (StringUtils.isBlank(ImgUrl)){
            return ApiResultJson.errorMes(ApiResultJson.NO_DATA,"当前站点没有图片");
        }
        JSONObject obj = new JSONObject();
        obj.put("ImgUrl",ImgUrl);
        return ApiResultJson.successResult(ApiResultJson.SUCCESS,"",obj);
    }
}
